import router,{loadAsyncRoute} from "./router"
import store from "./store"
import userApi from "./api/user"
import utils from "./utils/utils"


router.beforeEach(async (to,from,next)=>{
    // 获取vuex里面的token,
    let token = store.state.userInfo ? store.state.userInfo.token : ""
    //如果token不存在,则表示用户没有登录
    if(!token){
        //判断跳转的是否登录页页面
        if(to.path == "/login"){
            next()
        }else{
            //如果跳转的不是登录页,则进入登录页
            next("/login")
        }
    }else{
        //获取vuex里面的menuList
        let menuList = store.state.menuList || "";
        //如果获取到了,则进入主页
         if(menuList){
           next()
         }else{
            //如果没有获取到,则重新调用结偶,获取菜单的数据
            let res = await userApi.getPermissionList();
            store.commit("saveMenuList",res.menuList);
            store.commit("saveActionList",res.actionList);
            if(res){
                //获取到了,则进入主页
                next()
            }else{
                //否则重新登录
                next("/login")
            }
         }
    }
    loadAsyncRoute()
})

//判断要进入的路由是否在所有的路由里面存在,如果存在,则给函数返回为true,否在返回为false
function checkPermission(path){
   
    //1. 要进入的路由已经获取到了 , path

    //2. 获取到所有的路由
    let allRoutes = router.getRoutes()

    //3. 过滤进入路由是否在所有路由中存在
    let hasPermission = allRoutes.filter((item,index)=> {
        return item.path == path
    })


    if(hasPermission.length > 0){
        return true
    }else{
        return false;
    }
}

// let menuList = store.state.menuList;
        // console.log(menuList);
        // if(menuList){
        //     next()
        //     if(checkPermission(to.path)){
        //         next()
        //     }else{
        //         next({path : "/404"})
        //     }
        // }else{
        //     next("/login")
        // }